package com.gs.m_business_authority

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.gs.common.BaseStateCallback
import com.gs.common.constant.StateCode

class BusinessAuthorityPersistent(context: Context) {

    private val businessAuthorityModel by lazy { BusinessAuthorityModel.getInstance(context) }
    private val handler = Handler(Looper.getMainLooper())

    fun dealAuthority(username: String, isBusiness: Boolean ,callback: OnDoDealAuthorityStateCallback) {
        Thread{
            businessAuthorityModel.dealAuthority(username, isBusiness){
                when (it) {
                    StateCode.STATE_LOADING -> {
                        handler.post {
                            callback.onDealAuthorityLoading(isBusiness)
                        }
                    }
                    StateCode.STATE_SUCCESS -> {
                        handler.post {
                            callback.onDealAuthoritySuccess(isBusiness)
                        }
                    }
                    StateCode.STATE_FAILED -> {
                        handler.post {
                            callback.onDealAuthorityFailed(isBusiness)
                        }
                    }
                    StateCode.NETWORK_ERROR -> {
                        handler.post {
                            callback.onNetworkError()
                        }
                    }
                    StateCode.SERVER_ERROR -> {
                        handler.post {
                            callback.onServerError()
                        }
                    }
                    StateCode.UNKNOWN_ERROR -> {
                        handler.post {
                            callback.onUnknownError()
                        }
                    }
                }
            }
        }.start()
    }

    interface OnDoDealAuthorityStateCallback: BaseStateCallback{
        fun onDealAuthorityLoading(isBusiness: Boolean){}
        fun onDealAuthoritySuccess(isBusiness: Boolean)
        fun onDealAuthorityFailed(isBusiness: Boolean)
    }

    companion object{
        private var instance: BusinessAuthorityPersistent? = null

        fun getInstance(context: Context): BusinessAuthorityPersistent {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = BusinessAuthorityPersistent(context)
                    }
                }
            }
            return instance!!
        }
    }
}